package com.ccbooks.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class BooksDao {

	private Context context;
	private DBHelper helper;
	private SQLiteDatabase db;

	private static BooksDao dao;

	private BooksDao() {
	}

	public static BooksDao getDao(Context context) {
		if (dao == null) {
			dao = new BooksDao();
		}
		dao.context = context;
		return dao;
	}

	// ����ݿ�
	public void open() throws SQLException {
		helper = DBHelper.getHelper(context);
		if (db == null || !db.isOpen()) {
			db = helper.getWritableDatabase();
		}
	}

	// �ر���ݿ�
	public void close() throws SQLException {
		if(helper!=null){
		helper.close();
		}
	}
	
	public Cursor exec(String sql) throws SQLException{
		this.open();
		return db.rawQuery(sql, null);
	}

	// ������ݿⷽ����
	// ������ݿ�
	public void saveOrUpdate(String tablename, String bookname) {

	}

	// �����������
	public Cursor select(String table,String limit) throws SQLException {
		return select(false,table, null, null, null, null, limit);
	}

	public Cursor select(boolean distinct,String table, String[] columns, String selection,
			String[] selectionArgs, String orderBy, String limit)
			throws SQLException {
		this.open();
		// query(boolean distinct, String table, String[] columns, String
		// selection, String[] selectionArgs, String groupBy, String having,
		// String orderBy, String limit)
		Cursor cursor = db.query(distinct, table, null, selection,
				selectionArgs, null, null, orderBy, limit);
		return cursor;
	}

	// ȡ������
	public int count(String table) {
		Cursor cursor = select(false,table, new String[] { "_id" }, null, null, null,
				null);
		int count = cursor.getCount();
		cursor.close();
		return count;
	}

	public long insert(String table,ContentValues cv) throws SQLException

	{
		this.open();
		long row = db.insert(table, null, cv);
		this.close();
		return row;

	}

	public void delete(String table,int id) throws SQLException

	{

		this.open();

		String where = DBHelper.ID + "=?";

		String[] whereValue = { Integer.toString(id) };

		db.delete(table, where, whereValue);

	}

	public void deleteAll(String table) throws SQLException {
		this.open();
		db.delete(table, null, null);
		db.close();
	}

	public void update(String table,int id, ContentValues cv) throws SQLException

	{

		this.open();

		String where = DBHelper.ID + "=?";

		String[] whereValue = { Integer.toString(id) };

		db.update(table, cv, where, whereValue);


	}

}
